import json
from django.db.models import Count
from django.shortcuts import render
from django.views import View
from news.models import Tag
from utils.res_code.status_code import Code, error_map
from utils.res_code.status_json import status_json


class AdminIndexView(View):
    """
    后台管理index
    """

    def get(self, request):
        return render(request, 'admin/index.html')


class AdminTagsManage(View):
    """
    后台文章标签管理
    """

    def get(self, request):
        """
        加载数据
        :param request:
        :return:
        """
        tags = Tag.objects.values('id', 'name').annotate(count=Count('articles')).filter(is_delete=False).all()
        return render(request, 'admin/article_tags_manage.html', locals())

    def post(self, request):
        """
        添加标签
        :param request:
        :return:
        """
        json_data = request.body
        if not json_data:
            return status_json(no=Code.PARAMERR, msg=error_map[Code.PARAMERR])
        json_dict = json.loads(json_data.decode('utf-8'))
        tag_name = json_dict.get('name').strip()
        if len(tag_name) > 20:
            return status_json(no=Code.PARAMERR, msg="标签长度超出限制")
        if tag_name:
            tag_instance, tag_create_boolean = Tag.objects.get_or_create(name=tag_name)
            # get_or_create返回一个元祖，第一个元素是Tag的实例，第二个元素为一个boolean，查询时为False，创建时为True
            if tag_create_boolean:
                tag_info = {
                    'id': tag_instance.id,
                    'name': tag_instance.name
                }
                # tag_info为添加的标签信息
                # print(tag_info)
                return status_json(msg="标签添加成功", data=tag_info)
            else:
                if tag_instance.is_delete == True:
                    # 因为tag.name是唯一键，如果该标签已被删除（is_delete=True）,不可创建另一个name=tag_name的数据，
                    # 而是直接将假删的数据字段is_delete改为False
                    tag_instance.is_delete = False
                    tag_instance.save(update_fields=['is_delete'])
                    return status_json(msg="标签添加成功")
                return status_json(no=Code.DATAEXIST, msg="标签已存在，请勿重复创建")
        else:
            return status_json(no=Code.PARAMERR, msg="标签名不能为空")

    def put(self, request, tag_id):
        """
        更新标签
        :param request:
        :param tag_id:
        :return:
        """
        json_data = request.body
        if not json_data:
            return status_json(no=Code.PARAMERR, msg=error_map[Code.PARAMERR])
        json_dict = json.loads(json_data.decode('utf-8'))
        tag_name = json_dict.get('name').strip()
        if len(tag_name) > 20:
            return status_json(no=Code.PARAMERR, msg="标签长度超出限制")
        if not tag_name:
            return status_json(no=Code.PARAMERR, msg="标签名不能为空")
        if Tag.objects.filter(name=tag_name).exists():
            return status_json(no=Code.DATAEXIST,msg="标签名已存在")

        tag=Tag.objects.filter(id=tag_id,is_delete=False).first()
        if not tag:
            return status_json(no=Code.DBERR,msg="标签不存在")
        if tag_name == tag.name:
            return status_json(no=Code.DBERR, msg="标签名未变化")
        tag.name=tag_name
        tag.save(update_fields=['name',])
        return status_json(msg="标签更新成功")
    def delete(self, request, tag_id):

        """
        删除标签
        :param request:
        :param tag_id:
        :return:
        """
        tag = Tag.objects.filter(id=tag_id, is_delete=False).first()
        if tag:
            tag.is_delete = True
            tag.save(update_fields=['is_delete', ])
            # 只更新is_delete字段，提升sql性能
            return status_json(msg="删除标签成功")
        else:
            return status_json(no=Code.PARAMERR, msg="标签不存在")
